package com.cloud.wms.ui.in.fragment;

import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.cloud.core.eventBus.Event;
import com.cloud.core.utils.TimeUtils;
import com.cloud.widget.EditTextDel;
import com.cloud.widget.ScanText;
import com.cloud.widget.expand.ExpandLayout;
import com.cloud.wms.R;
import com.cloud.wms.base.BaseViewPagerFragment;
import com.cloud.wms.config.EventConfig;
import com.cloud.wms.ui.in.contract.InShelfContract;
import com.cloud.wms.ui.in.entity.InCommodityEntity;
import com.cloud.wms.ui.in.entity.InOrderEntity;
import com.cloud.wms.ui.in.entity.ShelfBatchEntity;
import com.cloud.wms.ui.in.presnter.InShelfPresenter;
import com.cloud.wms.ui.in.shelf.SelectBatchActivity;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.widget.dialog.TaskCompleteDialog;
import com.trello.rxlifecycle3.LifecycleTransformer;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Author:Chen
 * @Date: 2021-01-24 16:59
 * @Description:
 */
public class ShelfSingleFragment extends BaseViewPagerFragment<InShelfPresenter> implements InShelfContract.View {
    @BindView(R.id.scan_text)
    ScanText scanText;
    @BindView(R.id.btn_good)
    CheckedTextView btnGood;
    @BindView(R.id.btn_bad)
    CheckedTextView btnBad;
    @BindView(R.id.tv_member_name)
    TextView tvMemberName;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.tv_recommend_pos)
    TextView tvRecommendPos;
    @BindView(R.id.et_shelf_pos)
    EditTextDel etShelfPos;
    private InOrderEntity inOrder;
    private InCommodityEntity commodityEntity;
    private BaseQuickAdapter<InCommodityEntity, BaseViewHolder> mAdapter;
    private TaskEntity taskEntity;
    private String beginTime;

    @Override
    protected int getResId() {
        return R.layout.fragment_in_shelf_single;
    }

    @Override
    protected void setupComponent() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected void initEvent(Bundle bundle) {
        beginTime = TimeUtils.getCurrentDateAndTime();
        inOrder = getArguments().getParcelable("InOrder");
        taskEntity = getArguments().getParcelable("Task");
        if (inOrder != null)
            tvMemberName.setText(inOrder.getMemberName());
        else
            tvMemberName.setText(taskEntity.getMemberName());
        tvRecommendPos.setTag(false);
        btnSubmit.setEnabled(false);
        btnGood.setChecked(true);
        btnBad.setChecked(false);
        etShelfPos.setOnKeyListener(onKeyListenerImp);

        rvList.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = new BaseQuickAdapter<InCommodityEntity, BaseViewHolder>(R.layout.item_common_commodity) {
            @Override
            protected void convert(BaseViewHolder helper, InCommodityEntity item) {
                helper.setText(R.id.tv_commodity_name, item.getCommodityName())
                        .setText(R.id.tv_commodity_code, item.getBarCode())
                        .setText(R.id.tv_commodity_type, item.getStockTypeName())
                        .setText(R.id.tv_commodity_amount, item.getAmount() + "")
                        .setText(R.id.tv_produce_date, item.getProductionDate())
                        .setText(R.id.tv_deadline_date, item.getExpirationDate())
                        .setText(R.id.tv_in_date, item.getInDate())
                        .setText(R.id.tv_pos_code, item.getPosCode())
                        .setGone(R.id.tv_pos_title, false)
                        .setGone(R.id.tv_pos_code, false);

                ImageView ivArrow = helper.getView(R.id.iv_arrow);
                ExpandLayout expand = helper.getView(R.id.expand_layout);
                expand.setOnExpansionUpdateListener((expansionFraction, state) -> ivArrow.setRotation(expansionFraction * 180));
                helper.getView(R.id.ll_title_content).setOnClickListener(v -> expand.toggle(true));
            }
        };
        rvList.setItemAnimator(new DefaultItemAnimator());
        rvList.setAdapter(mAdapter);

        mAdapter.setNewInstance(new ArrayList<InCommodityEntity>());
    }

    @Override
    public ScanText getScanText() {
        return scanText;
    }

    @Override
    protected void onScanHandle(String result, int resultCode) {
        super.onScanHandle(result, resultCode);
        if (etShelfPos.isFocused()) {
            if (!((boolean) tvRecommendPos.getTag())) {
                info("请先扫描商品");
                return;
            }
            etShelfPos.setText(result);
            etShelfPos.setSelection(result.length());
            int commodityType = 1;
            if (btnBad.isChecked()) commodityType = 2;
            mPresenter.checkPosCode(result, commodityType);
        } else {
            scanText.addHistory(result);
            int commodityType = 1;
            if (btnBad.isChecked()) commodityType = 2;
            mPresenter.checkCommodityCode(inOrder != null ? String.valueOf(inOrder.getInID()) :  taskEntity.getMainBillID() + "", result, commodityType);
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onSuccess(Message message) {
        switch (message.what) {
            case InShelfPresenter.IN_CHECK_COMMODITY_CODE:
                InCommodityEntity obj = (InCommodityEntity) message.obj;
                ArrayList<ShelfBatchEntity> list = new ArrayList<>();
                for (int i = 0; i < obj.getProductBatchList().size(); i++) {
                    ShelfBatchEntity batchEntity = obj.getProductBatchList().get(i);
                    int sum = 0;
                    for (int j = 0; j < mAdapter.getData().size(); j++) {
                        InCommodityEntity inCommodityEntity = mAdapter.getData().get(j);
                        if (obj.getCommodityId() == inCommodityEntity.getCommodityId()
                                && inCommodityEntity.getProductBatchID() == batchEntity.getProductBatchID())
                            sum += inCommodityEntity.getAmount();
                    }
                    if (sum < (batchEntity.getPlanAmount() - batchEntity.getUpAmount())) {
                        list.add(batchEntity);
                    }
                }
                if (list.isEmpty()) {
                    info("当前商品清点批次已扫描或上架完成！");
                    return;
                }
                obj.setProductBatchList(list);

                commodityEntity = obj;
                tvRecommendPos.setText(commodityEntity.getPosCode());
                tvRecommendPos.setTag(true);
                etShelfPos.requestFocus();
                break;
            case InShelfPresenter.IN_CHECK_POS_CODE:
                success("库位扫描验证成功!");
                int commodityType = 1;
                if (btnBad.isChecked()) commodityType = 2;
                commodityEntity.setStockType(commodityType);
                commodityEntity.setPosCode(message.obj.toString());
                SelectBatchActivity.start(getContext(), inOrder, commodityEntity, true);
                break;
            case InShelfPresenter.IN_BATCH_SINGLE_SUBMIT:
                success("上架提交成功!");
                resetView();
                break;
            case InShelfPresenter.CHECK_COMPLETE:
                new TaskCompleteDialog(getActivity()).show();
                break;
        }
    }

    @Override
    protected boolean isUseEventBus() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onEventCome(Event event) {
        if (event == null) {
            return;
        }
        switch (event.getCode()) {
            case EventConfig.SHELF_SELECT_BATCH:
                etShelfPos.setText("");
                scanText.getFocus();
                ShelfBatchEntity batchEntity = (ShelfBatchEntity) event.getData();
                tvRecommendPos.setTag(false);
                for (int i = 0; i < mAdapter.getData().size(); i++) {
                    InCommodityEntity commodity = mAdapter.getData().get(i);
                    if (commodity.getProductBatchID() == batchEntity.getProductBatchID()
                            && commodity.matchBarCode(commodityEntity.getBarCode())
                            && commodity.getPosCode().equalsIgnoreCase(commodityEntity.getPosCode())
                            && commodity.getStockType() == commodityEntity.getStockType()) {
                        if (commodity.getAmount() < commodity.getTotalAmount()) {
                            commodity.setAmount(commodity.getAmount() + 1);
                            mAdapter.notifyDataSetChanged();
                            success("批次选择成功！");
                        } else {
                            info("当前批次商品已扫描完成");
                        }
                        return;
                    }
                }
                success("批次选择成功！");
                commodityEntity.setProductBatchID(batchEntity.getProductBatchID());
                commodityEntity.setProductionDate(batchEntity.getProductionDate());
                commodityEntity.setExpirationDate(batchEntity.getExpirationDate());
                commodityEntity.setInDate(batchEntity.getInDate());
                commodityEntity.setAmount(1);
                commodityEntity.setTotalAmount(batchEntity.getPlanAmount() - batchEntity.getUpAmount());
                mAdapter.addData(0, commodityEntity);
                btnSubmit.setEnabled(true);
                break;
        }
    }

    private void resetView() {
        mAdapter.getData().clear();
        mAdapter.notifyDataSetChanged();
        commodityEntity = null;
        btnSubmit.setEnabled(false);
        btnGood.setChecked(true);
        btnBad.setChecked(false);
        tvRecommendPos.setText("");
        tvRecommendPos.setTag(false);
        etShelfPos.setText("");

        mPresenter.loadInCommodityList(inOrder != null ? String.valueOf(inOrder.getInID()) :  taskEntity.getMainBillID() + "", false);
    }

    @OnClick({R.id.btn_good, R.id.btn_bad, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_good:
                btnGood.setChecked(true);
                btnBad.setChecked(false);
                break;
            case R.id.btn_bad:
                btnGood.setChecked(false);
                btnBad.setChecked(true);
                break;
            case R.id.btn_submit:
                mPresenter.submitSingleAndBatchShelf(taskEntity, inOrder, mAdapter.getData(), beginTime);
                break;
        }
    }

    @Override
    public <R> LifecycleTransformer<R> toLifecycle() {
        return bindToLifecycle();
    }

    public static BaseViewPagerFragment newInstance(Bundle bundle) {
        ShelfSingleFragment fragment = new ShelfSingleFragment();
        fragment.setArguments(bundle);
        return fragment;
    }
}
